package com.xpgk.webSocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.jfinal.log.Log;

@ServerEndpoint(value = "/websocket/{param}", configurator = HttpSessionConfigurator.class)
public class WebSocketController {

	private static final Log log = Log.getLog(WebSocketController.class);

	public static final Map<String, Object> connections = new HashMap<String, Object>();

	private String nickname;
	private Session session;

	@OnOpen
	public void onOpen(@PathParam(value = "param") String param, Session session, EndpointConfig config) {
		this.session = session;
		nickname = param;
		WebSocketController oldClient = (WebSocketController) connections.get(param);
		if (null == oldClient) {
			connections.put(nickname, this);
			String message = String.format("* %s %s", nickname, "上线");
			broadcast(message);
		}
	}

	@OnClose
	public void onClose(Session session) {
		connections.remove(nickname);
		String message = String.format("* %s %s", nickname, "下线");
		broadcast(message);
	}

	@OnMessage
	public void onMessage(String requestJson, Session session) {
		// try {
		// session.getBasicRemote().sendText(requestJson);
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		String filteredMessage = String.format("%s: %s", nickname, HTMLFilter.filter(requestJson.toString()));
		// broadcast(filteredMessage);
		sendAll(filteredMessage);
	}

	/**
	 * 消息发送方法
	 * 
	 * @param msg
	 */
	private static void broadcast(String msg) {
		sendAll(msg);
		// if (msg.indexOf("Guest0") != -1) {
		// sendUser(msg);
		// } else {
		// sendAll(msg);
		// }
	}

	/**
	 * 向所有用户发送
	 * 
	 * @param msg
	 */
	public static void sendAll(String msg) {
		for (String key : connections.keySet()) {
			WebSocketController client = null;
			try {
				client = (WebSocketController) connections.get(key);
				synchronized (client) {
					client.session.getBasicRemote().sendText(msg);
				}
			} catch (IOException e) {
				log.debug("Chat Error: Failed to send message to client", e);
				connections.remove(client);
				try {
					client.session.close();
				} catch (IOException e1) {
					// Ignore
				}
				String message = String.format("* %s %s", client.nickname, "has been disconnected.");
				broadcast(message);
			}
		}
	}

	/**
	 * 向指定用户发送消息
	 * 
	 * @param msg
	 */
	public static void sendUser(String username,String msg) {
		//WebSocketController c = (WebSocketController) connections.get("Guest0");
		
		WebSocketController c = (WebSocketController) connections.get(username);
		try {
			c.session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			log.debug("Chat Error: Failed to send message to client", e);
			connections.remove(c);
			try {
				c.session.close();
			} catch (IOException e1) {
				// Ignore
			}
			String message = String.format("* %s %s", c.nickname, "has been disconnected.");
			broadcast(message);
		}
	}

}
